<!DOCTYPE html>
<html>
<head>
  <script src="three.min.js"></script>
  <!-- ---------------------------------------------------------------------------

    一个动画的例子

  ----------------------------------------------------------------------------- -->
  <script>
    let scene, camera, renderer, id, ballMesh,
        ballRadius = 0.5,
        maxHeight = 5,
        isMoving = false,
        v = 0,
        a = -0.01

    function init() {
      renderer = new THREE.WebGLRenderer({
        canvas: document.getElementById('mainCanvas')
      })

      scene = new THREE.Scene()

      camera = new THREE.PerspectiveCamera(80, 400 / 300, 1, 10)
      camera.position.set(3, 3, 5)
      camera.lookAt(new THREE.Vector3(0, 0, 0))
      scene.add(camera)

      let light = new THREE.DirectionalLight(0xffffff)
      light.position.set(2, 10, 5)
      scene.add(light)

      // ball
      ballMesh = new THREE.Mesh(
          new THREE.SphereGeometry(ballRadius, 16, 8),
          new THREE.MeshLambertMaterial({color: 0xffff00})
      )
      ballMesh.position.y = ballRadius
      scene.add(ballMesh)

      // plant
      let loader = new THREE.TextureLoader()
      loader.load('./img/chess.png', function (texture) {
        texture.wrapS = texture.wrapT = THREE.RepeatWrapping
        texture.repeat.set(4, 4)
        let plane = new THREE.Mesh(
            new THREE.PlaneGeometry(5, 5),
            new THREE.MeshLambertMaterial({map: texture})
        )
        plane.rotation.x = -Math.PI / 2
        scene.add(plane)

        renderer.render(scene, camera)
      })

      id = requestAnimationFrame(draw)

      drop()
    }

    function draw() {
      renderer.render(scene, camera)
      if(isMoving){
        ballMesh.position.y += v
        v += a
        if (ballMesh.position.y <= ballRadius) {
          v = -v * .9
        }
        if (Math.abs(v) < 0.001) {
          isMoving = false
          ballMesh.position.y = ballRadius
        }
      }
      id = requestAnimationFrame(draw)
    }

    function drop() {
      isMoving = true
      ballMesh.position.y = maxHeight
      v = 0;
    }

    function stop() {
      if (!id) {
        cancelAnimationFrame(id)
        id = null
      }
    }

  </script>
</head>
<body onload="init()">
<canvas id="mainCanvas" width="400px" height="300px"></canvas>
</body>
</html>
